import PlatUtils from "./PlatUtils";
import { utils } from "./Utils";

const { ccclass, property } = cc._decorator;

@ccclass
export default class WechatTool {

    /**
     * 服务器配置信息
     */
    public configData: any = null;

    public init() {
        if(PlatUtils.IsWechat){
            this._loadConfig();

            // 开启右上角转发
            if (PlatUtils.IsWechat) {
                wx.showShareMenu();
                wx.onShareAppMessage(this._getShareInfo());
            }
        }
    }

    _loadConfig() {
        if (PlatUtils.IsWechat) {
            let url: string = "https://apps.youletd.com/gs?m=gconfig&app_id=" + utils.config.wechatconfig.appID;
            console.log("url = ", url);
            let self = this;
            wx.request({
                url: url, 
                data: {
                },
                header: {
                    'content-type': 'application/json' // 默认值
                },
                success(res) {
                    if (res.data) {
                        console.log("配置数据拉取成功！");
                        self.configData = res.data;
                        cc.game.emit("WeChatPlatMessage", { type: "ConfigLoaded" });
                    } else {
                        console.log("配置数据不存在!");
                    }
                },
                fail(res) {
                    console.log("配置数据拉取失败！");
                    console.log(PaymentResponse);
                }
            });
        }
    }

    public navigateToMiniProgram(id: string) {
        if (PlatUtils.IsWechat) {
            wx.navigateToMiniProgram({
                appId: id,
                success(res) {
                },
                fail(res) {
                    cc.log("跳转失败！", id);
                }
            });
        }
    }

    public getSystemInfo() {
        if (PlatUtils.IsWechat) {
            return wx.getSystemInfoSync();
        }
    }

    public previewImage(url: string) {
        if (PlatUtils.IsWechat) {
            wx.previewImage({
                urls: [url] // 需要预览的图片http链接列表
            });
        }
    }

    public share(){
        if(PlatUtils.IsWechat){
            wx.shareAppMessage(this._getShareInfo());
        }
    }

    _getShareInfo(){
        if(PlatUtils.IsWechat){
            if(this.configData && this.configData.shares && this.configData.shares.sy_title && this.configData.shares.sy_img){
                return {
                    title:this.configData.shares.sy_title,
                    imageUrl:this.configData.shares.sy_img
                };
            }
        }

        return {};
    }

}
